﻿using UnityEngine;
using System.Collections;

public class rollHPTarget : MonoBehaviour {
	#region Member
	[SerializeField]UISlider scrollBar;
	[SerializeField]UISprite bgSprite;
	/// <summary>
	/// 滚动速度
	/// </summary>
	[SerializeField]float speed = 1;
	/// <summary>
	/// color[0]代表 
	/// 最底下的背景条 
	/// 只会被bgSprite使用
	/// </summary>
	[SerializeField]Color[] colors;
	int _nowindex;
	//0-colors.length
	float _targetScrollBarValue = 0;
	//0-colors.length 
	float _nowScrollBarValue= 0;

	/// <summary>
	/// 用于插值计算
	/// </summary>
	float _time;
	/// <summary>
	/// 缓存滚动开始数值
	/// </summary>
	float _cachestartvalue;

	/// <summary>
	/// 实际参与计算的滚动条数 -1是因为去掉黑色底板
	/// </summary>
	/// <value>The length of the colors.</value>
	int scrollBarCount{
		get{ return colors.Length - 1; }
	}
	/// <summary>
	/// 当前处于第几条滚动条
	/// </summary>
	int nowindex{
		set{ 
			if (_nowindex != value) {
				_nowindex = value;
				scrollBar.foregroundWidget.color = colors [value+1];
				bgSprite.color = colors [value];
			}
		}
		get{ 
			return _nowindex;
		}
	}
	#endregion
	#region Active
	void Awake(){
		InitFSM ();
		_nowScrollBarValue = scrollBarCount;
		nowindex = scrollBarCount -1;
	}
	void Update(){
		if(Input.GetKeyDown("1")){
			SetValue (Random.Range(0,1f));
		}
		if(Input.GetKeyDown("2")){
			SetValueNow (Random.Range(0,1f));
		}
		fsm.UpdateState (Time.deltaTime);
	}
	void UpdateSlider(float value){
		nowindex = (int)value;
		scrollBar.value = value % 1;
	}
	#endregion
	#region Event
	/// <summary>
	/// 立即重置滚动条到指定位置
	/// </summary>
	/// <param name="value">Value.</param>
	public void SetValueNow(float value){
		value = Mathf.Clamp (value, 0, 1);
		fsm.SetState (idle);
		UpdateSlider (value * scrollBarCount);
	}
	/// <summary>
	/// 使用平滑插值
	/// </summary>
	/// <param name="value">Value.</param>
	public void SetValue(float value){
		value = Mathf.Clamp (value, 0, 1);
		_targetScrollBarValue = value*scrollBarCount;
		if (fsm.IsState (play))
			fsm.StartAnew ();
		else
			fsm.SetState (play);
	}
	#endregion
	#region FSM
	FSM fsm = new FSM();
	StatePath idle = new StatePath("Idle");
	StatePath play = new StatePath("play");
	void InitFSM(){
		fsm.AddState (idle);
		fsm.AddState (play, OnPlayEnter, OnPlayUpdate);
	}

	void OnPlayEnter(){
		_time = Mathf.Abs (_targetScrollBarValue - _nowScrollBarValue) / speed;
		_cachestartvalue = _nowScrollBarValue;
	}
	void OnPlayUpdate(float dt){
		_nowScrollBarValue = Mathf.Lerp (_cachestartvalue, _targetScrollBarValue, fsm.stateTime / _time);
		UpdateSlider (_nowScrollBarValue);

		if (fsm.stateTime > _time)
			fsm.SetState (idle);
	}
	#endregion
}
